package com.example.my.nanyibangz.ui.dapeidownclick;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.my.nanyibangz.R;
import com.example.my.nanyibangz.base.BaseActivity;
import com.example.my.nanyibangz.bean.DanPinTypeClickBeans;
import com.example.my.nanyibangz.bean.DanPinTypeClickCommentBeans;
import com.example.my.nanyibangz.config.DanPinUrlConfig;
import com.example.my.nanyibangz.ui.danpintypeclick.DanPinGoodCommentFragment;
import com.example.my.nanyibangz.ui.danpintypeclick.DanPinGoodInfoFragment;
import com.example.my.nanyibangz.ui.danpintypeclick.DanPinTypeClickLowerActivity;
import com.example.my.nanyibangz.ui.danpintypeclick.DanPinTypeClickLowerAdAdpter;
import com.example.my.nanyibangz.ui.danpintypeclick.DanPinTypeClickLowerContact;
import com.example.my.nanyibangz.ui.danpintypeclick.DanPinTypeClickLowerPrenster;
import com.example.my.nanyibangz.ui.danpintypeclick.ShowWebImageActivity;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2016/10/17.
 */
@SuppressLint("SetJavaScriptEnabled")
public class GrideClickActivity extends BaseActivity implements DanPinTypeClickLowerContact.View {

    @Bind(R.id.vp_typeclick)
    ViewPager vpTypeclick;
    @Bind(R.id.ll_type_point)
    LinearLayout llTypePoint;
    @Bind(R.id.txt_typeclick_sprice)
    TextView txtTypeclickSprice;
    @Bind(R.id.txt_typeclick_coupon_price)
    TextView txtTypeclickCouponPrice;
    @Bind(R.id.txt_typeclick_title)
    TextView txtTypeclickTitle;
    @Bind(R.id.txt_type_info)
    TextView txtTypeInfo;
    @Bind(R.id.txt_type_comment)
    TextView txtTypeComment;
    @Bind(R.id.ll_type_click_fg)
    FrameLayout llTypeClickFg;
    @Bind(R.id.web_typeclick)
    WebView webTypeclick;
    @Bind(R.id.rbt_type_collection)
    RadioButton rbtTypeCollection;
    @Bind(R.id.rbt_type_share)
    RadioButton rbtTypeShare;
    @Bind(R.id.rbt_type_add_cart)
    RadioButton rbtTypeAddCart;
    @Bind(R.id.rbt_type_goto_mail)
    RadioButton rbtTypeGotoMail;
    @Bind(R.id.rg_typeclick)
    RadioGroup rgTypeclick;
    private DanPinTypeClickLowerAdAdpter ad_adapter;//轮播图的adapter;
    private int item_id;//用于接收上衣页面传递过来的，item_id，拼接地址。
    private DanPinTypeClickBeans.DataBean dpbeans;//用于接收网络下载的每一项的实体对象
    private DanPinTypeClickLowerPrenster presenter;//中间者
    private List<ImageView> imageViewList;//存放imageview的list集合。
    private int curIndex = 0;//默认起始索引。
    FragmentManager fragmentManager;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String[] imgStrs = (String[]) msg.obj;
                imageViewList = new ArrayList<>();
                for (int i = 0; i < imgStrs.length; i++) {
                    ImageView imageView = new ImageView(GrideClickActivity.this);
                    Picasso.with(GrideClickActivity.this).load(imgStrs[i]).resize(360, 300).into(imageView);
                    imageViewList.add(imageView);
                }
                initPoints(imageViewList.size());//初始化图片小圆点
                ad_adapter = new DanPinTypeClickLowerAdAdpter(imageViewList);
                vpTypeclick.setAdapter(ad_adapter);
                startAutoScroll();// 自动播放
                MyVpChagnerListenr();//广告条viewpager的滑动监听事件

            }
        }
    };
    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        initGet();
        initUrlMap();
    }
    @Override
    public int getLayoutId() {
        return R.layout.layout_pullrefrsh;
    }
    private void initGet(){
        Intent intent=getIntent();
        item_id=intent.getExtras().getInt("item_id");

    }

    private void initUrlMap(){
        Map<String, String> params = new HashMap<>();
        params.put(DanPinUrlConfig.Params.Age, 19 + "");
        params.put(DanPinUrlConfig.Params.Channel, DanPinUrlConfig.DefaultVaule.Channel_VALUE);
        params.put(DanPinUrlConfig.Params.Hkm_sign2, DanPinUrlConfig.DefaultVaule.Hkm_sign2_VALUE);
        params.put(DanPinUrlConfig.Params.Item_id, item_id+"");
        params.put(DanPinUrlConfig.Params.Member_id, DanPinUrlConfig.DefaultVaule.Member_id_VALUE);
        params.put(DanPinUrlConfig.Params.Member_type, DanPinUrlConfig.DefaultVaule.Member_type_VALUE);
        params.put(DanPinUrlConfig.Params.Random_key, DanPinUrlConfig.DefaultVaule.Random_key_VALUE);
        params.put(DanPinUrlConfig.Params.System_name, DanPinUrlConfig.DefaultVaule.System_name_VALUE);
        params.put(DanPinUrlConfig.Params.VersionCode, DanPinUrlConfig.DefaultVaule.VersionCode_VALUE);
        presenter = new DanPinTypeClickLowerPrenster(this);
        presenter.getVerticalTypeLowerBeanFromNet(params);
    }

    @Override
    public void getVerticalTypeLowerSuccess(DanPinTypeClickBeans danPinTypeClickBeans) {
        Log.i("item", "bens" + danPinTypeClickBeans);
        dpbeans = danPinTypeClickBeans.getData();
        setData();
        SendDataToInfoFg();
        GoodsInfoClick();  //商品信息
        GoodsCommentClick();//商品评论点击
    }

    @Override
    public void getVerticalTypeLowerFailed(String msg) {

    }

    @Override
    public void getVerticalGoodsCommentSuccess(DanPinTypeClickCommentBeans danPinTypeClickCommentBeans) {

    }

    @Override
    public void getVerticalGoodsCommentFailed(String msg) {

    }
    //以下是实现广告banner的轮播
    // 初始化图片轮播的小圆点和目录
    private void initPoints(int count) {
        for (int i = 0; i < count; i++) {

            ImageView iv = new ImageView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    20, 20);
            params.setMargins(0, 0, 20, 0);
            iv.setLayoutParams(params);
            iv.setImageResource(R.mipmap.icon_next_one_normal);
            llTypePoint.addView(iv);

        }
        ((ImageView) llTypePoint.getChildAt(curIndex))
                .setImageResource(R.mipmap.icon_next_one_select);
    }
    // 自动播放
    private void startAutoScroll() {
        ScheduledExecutorService scheduledExecutorService = Executors
                .newSingleThreadScheduledExecutor();
        // 每隔4秒钟切换一张图片
        scheduledExecutorService.scheduleWithFixedDelay(new GrideClickActivity.ViewPagerTask(), 5,
                4, TimeUnit.SECONDS);
    }
    // 切换图片任务
    private class ViewPagerTask implements Runnable {
        @Override
        public void run() {

            GrideClickActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int count = ad_adapter.getCount();
                    vpTypeclick.setCurrentItem((curIndex + 1) % count);
                }
            });
        }
    }
    //广告viewpager滑动事件监听
    public void MyVpChagnerListenr() {
        vpTypeclick.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                ImageView imageView1 = (ImageView) llTypePoint.getChildAt(position);
                ImageView imageView2 = (ImageView) llTypePoint.getChildAt(curIndex);
                if (imageView1 != null) {
                    imageView1.setImageResource(R.mipmap.icon_next_one_select);
                }
                if (imageView2 != null) {
                    imageView2.setImageResource(R.mipmap.icon_next_one_normal);
                }
                curIndex = position;

            }

            boolean b = false;

            @Override
            public void onPageScrollStateChanged(int state) {
                //这段代码可不加，主要功能是实现切换到末尾后返回到第一张
                switch (state) {
                    case 1:// 手势滑动
                        b = false;
                        break;
                    case 2:// 界面切换中
                        b = true;
                        break;
                    case 0:// 滑动结束，即切换完毕或者加载完毕
                        // 当前为最后一张，此时从右向左滑，则切换到第一张
                        if (vpTypeclick.getCurrentItem() == vpTypeclick.getAdapter()
                                .getCount() - 1 && !b) {
                            vpTypeclick.setCurrentItem(0);
                        }
                        // 当前为第一张，此时从左向右滑，则切换到最后一张
                        else if (vpTypeclick.getCurrentItem() == 0 && !b) {
                            vpTypeclick.setCurrentItem(vpTypeclick.getAdapter()
                                    .getCount() - 1);
                        }
                        break;

                    default:
                        break;
                }
            }
        });
    }
    //给各个textview等赋值。
    @SuppressLint("SetJavaScriptEnabled")
    public void setData() {
        txtTypeclickSprice.setText(dpbeans.getPrice() + "");
        txtTypeclickCouponPrice.setText(dpbeans.getCouponPrice() + "");
        txtTypeclickCouponPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        txtTypeclickTitle.setText(dpbeans.getTitle());
        // String htmlString = dpbeans.getItemDescription().toString();
        String ui="<head>\n" +
                "     <style>\n" +
                "     .center_image { width: 100%}\n" +
                "     .hide_image { display: none}\n" +
                "     </style>\n" +
                "     </head><img class='center_image' src='https://img.alicdn.com/imgextra/i4/656010309/TB2OYr1uXXXXXb3XpXXXXXXXXXX_!!656010309.jpg'><img class='center_image' src='https://img.alicdn.com/imgextra/i2/656010309/TB208UcuXXXXXadXpXXXXXXXXXX_!!656010309.jpg'><img class='center_image' src='https://img.alicdn.com/imgextra/i4/656010309/TB20iQsuXXXXXa_XXXXXXXXXXXX_!!656010309.jpg'><img class='center_image' src='https://img.alicdn.com/imgextra/i2/656010309/TB2I8UquXXXXXbZXXXXXXXXXXXX_!!656010309.jpg'><img class='center_image' src='https://img.alicdn.com/imgextra/i4/656010309/TB2nrgAuXXXXXanXXXXXXXXXXXX_!!656010309.jpg'><img class='center_image' src='https://img.alicdn.com/imgextra/i1/656010309/TB2DTMCuXXXXXXZXXXXXXXXXXXX_!!656010309.jpg'><img class='center_image' src='https://img.alicdn.com/imgextra/i2/656010309/TB2B3Y1uXXXXXcjXpXXXXXXXXXX_!!656010309.jpg'><img class='center_image' src='https://img.alicdn.com/imgextra/i3/656010309/TB2KjAguXXXXXXMXpXXXXXXXXXX_!!656010309.jpg'><img class='center_image' src='https://img.alicdn.com/imgextra/i4/656010309/TB2fshcXb75VKBjy0FcXXbAkXXa_!!656010309.jpg'><script>\n" +
                "     var imgs = document.getElementsByClassName('center_image');\n" +
                "     for (var i = 0; i < imgs.length; i++) {\n" +
                "     imgs[i]['index']=i;\n" +
                "     imgs[i].addEventListener('load', function() {\n" +
                "     if (imgs[this.index].naturalWidth < 100) {\n" +
                "     this.className += ' hide_image';\n" +
                "     }\n" +
                "     });\n" +
                "     imgs[i].addEventListener('error', function() {\n" +
                "     this.className += ' hide_image';\n" +
                "     });\n" +
                "     }\n" +
                "     </script>";

        //启用javascript
        webTypeclick.getSettings().setJavaScriptEnabled(true);
//给webView添加js代码
        webTypeclick.loadData(ui,"text/html","utf-8");

        // 添加js交互接口类，并起别名 imagelistner  addJavaScriptInterface方式帮助我们从一个网页传递值到Android XML视图（反之亦然）。
        webTypeclick.addJavascriptInterface(new GrideClickActivity.JavascriptInterface(this), "imagelistner");
        // webTypeclick.addJavascriptInterface(new JavascriptInterface(this), "imagelistner");
        webTypeclick.setWebViewClient(new GrideClickActivity.MyWebViewClient());
        //加载轮播图的的地址
        String imgUrls = dpbeans.getPicUrls();
        final String[] imgs = imgUrls.split(",");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = Message.obtain();
                message.what = 1;
                message.obj = imgs;
                handler.sendMessage(message);
            }
        }).start();
    }
    private void addImageClickListner() {
        Log.i("zb","zlbhtml加载完成后调用listenter");
        // 这段js函数的功能就是，遍历所有的img，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
        webTypeclick.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.imagelistner.openImage(this.src);  " +
                "    }  " +
                "}" +
                "})()");
    }
    // js通信接口
    public class JavascriptInterface {

        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }

        // android混淆之后webview不响应js点击事件 在js的接口上面写上@JavascriptInterface。。。找了好久，在官方文档上找到的解决办法。
        //下面注解必须加上，不然在4.2以上的机子，js注入不响应事件。
        @android.webkit.JavascriptInterface
        public void openImage(String img) {
            System.out.println(img);
            Log.i("zb","zlb被点击了+openimage");
            Log.i("zb","image=="+img);
            Intent intent = new Intent();
            intent.putExtra("image", img);
            intent.setClass(context, ShowWebImageActivity.class);
            context.startActivity(intent);
            System.out.println(img);
        }
    }
    private class MyWebViewClient extends WebViewClient {

        //在点击请求的是链接是才会调用，重写此方法返回true表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边。
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            return super.shouldOverrideUrlLoading(view, url);
        }

        //在页面加载结束时调用。
        @Override
        public void onPageFinished(WebView view, String url) {

            view.getSettings().setJavaScriptEnabled(true);

            super.onPageFinished(view, url);
            // html加载完成之后，添加监听图片的点击js函数
            addImageClickListner();

        }

        //在页面加载开始时调用。
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.getSettings().setJavaScriptEnabled(true);

            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.i("zb","zlb被点击了"+false);
            super.onReceivedError(view, errorCode, description, failingUrl);

        }
    }
    //将danpintypeclickbeans传递给商品信息的bundle值。
    public void SendDataToInfoFg() {
        Log.i("zlb", "mei===" + true);
        txtTypeInfo.setTextColor(GrideClickActivity.this.getResources().getColor(R.color.colorSwipRef));
        txtTypeInfo.setBackground(GrideClickActivity.this.getResources().getDrawable(R.color.colorToolbar));
        Bundle bundle = new Bundle();
        bundle.putSerializable("index", dpbeans);
        DanPinGoodInfoFragment danPinGoodInfoFragment = new DanPinGoodInfoFragment();
        danPinGoodInfoFragment.setArguments(bundle);
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.ll_type_click_fg, danPinGoodInfoFragment);
        transaction.commit();
    }

    //商品信息点击
    public void GoodsInfoClick() {
        txtTypeInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txtTypeComment.setTextColor(GrideClickActivity.this.getResources().getColor(R.color.colorToolbar));
                txtTypeComment.setBackground(GrideClickActivity.this.getResources().getDrawable(R.drawable.type_txt_infoand_comshape));
                txtTypeInfo.setTextColor(GrideClickActivity.this.getResources().getColor(R.color.colorSwipRef));
                txtTypeInfo.setBackground(GrideClickActivity.this.getResources().getDrawable(R.color.colorToolbar));
                Bundle bundle = new Bundle();
                bundle.putSerializable("index", dpbeans);
                DanPinGoodInfoFragment danPinGoodInfoFragment = new DanPinGoodInfoFragment();
                danPinGoodInfoFragment.setArguments(bundle);
                fragmentManager = getSupportFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.replace(R.id.ll_type_click_fg, danPinGoodInfoFragment);
                transaction.commit();
            }
        });
    }

    //店铺品论点击
    public void GoodsCommentClick() {
        txtTypeComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txtTypeComment.setTextColor(GrideClickActivity.this.getResources().getColor(R.color.colorSwipRef));
                txtTypeComment.setBackground(GrideClickActivity.this.getResources().getDrawable(R.color.colorToolbar));
                txtTypeInfo.setBackground(null);
                txtTypeInfo.setBackground(GrideClickActivity.this.getResources().getDrawable(R.drawable.type_txt_infoand_comshape));
                txtTypeInfo.setTextColor(GrideClickActivity.this.getResources().getColor(R.color.colorToolbar));

                Bundle bundle = new Bundle();
                bundle.putString("IndexId", item_id+"");
                DanPinGoodCommentFragment danPinGoodInfoFragment = new DanPinGoodCommentFragment();
                danPinGoodInfoFragment.setArguments(bundle);
                fragmentManager = getSupportFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.replace(R.id.ll_type_click_fg, danPinGoodInfoFragment);
                transaction.commit();

            }
        });
    }
}
